package com.will.seed.websocket;

import java.util.concurrent.TimeUnit;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * Created by xiaoEigth on 2018/8/17.
 */
public class WebSocketServerInitializer extends ChannelInitializer<Channel> {

    @Value("${ws.path:/websocket}")
    private String wsUri;

    @Autowired
    private TextWebSocketFrameHandler textWebSocketFrameHandler;

    @Autowired
    private HttpRequestHandler httpRequestHandler;

    private final ChannelGroup group;

    public WebSocketServerInitializer(ChannelGroup group) {
        this.group = group;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));

        pipeline.addLast(new IdleStateHandler(0, 0, 1800, TimeUnit.SECONDS));
        pipeline.addLast(new WebSocketHeartbeatHandler());

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(httpRequestHandler);
        pipeline.addLast(new WebSocketServerProtocolHandler(wsUri));
        pipeline.addLast(textWebSocketFrameHandler);
    }
}